﻿using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace MyOCR.Picture
{
    //https://cloud.tencent.com/
    class TengXun_PictureHandleOCR : PictureHandle
    {
        string base64img;

        static TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
        Int64 currentTime = Convert.ToInt64(ts.TotalSeconds);

        public TengXun_PictureHandleOCR()
        {
        }

        public override string IdentifyImage(Image img)
        {
            var client = new RestClient("https://ocr.tencentcloudapi.com/");
            var request = new RestRequest(Method.POST);


            request.Timeout = 10000;
            request.AddHeader("host", "ocr.tencentcloudapi.com");
            // base64 string file picture,too long in the case we will omit string
            var bmp = GrayscaleImage(img);
            base64img = ImageToBase64(bmp);

            request.AddParameter("Action", "GeneralBasicOCR");//
            request.AddParameter("Version", "2018-11-19");
            request.AddParameter("Region", "ap-guangzhou");//

            request.AddParameter("Timestamp", currentTime);//
            request.AddParameter("Nonce", "1223455");//
            request.AddParameter("SecretId", Program._config.TengXun_Secret_Id);//
            request.AddParameter("Signature", getSign());
            request.AddParameter("ImageBase64", base64img);//

            IRestResponse response = client.Execute(request);

            //解析获取的json
            var lst = new List<string>();
            var content = response.Content;
            dynamic json = JsonConvert.DeserializeObject(content);
            foreach (var item in json.Response.TextDetections)
            {
                lst.Add(item.DetectedText.ToString());
            }
            return string.Join("\r\n", lst);
        }

        protected override string getSign()
        {
            string sign = string.Format("POSTocr.tencentcloudapi.com/?Action=GeneralBasicOCR&ImageBase64=" + base64img + "&Nonce=1223455&Region=ap-guangzhou&SecretId=" + Program._config.TengXun_Secret_Id + "&Timestamp="+ currentTime + "&Version=2018-11-19");


            return hash_hmac(sign, Program._config.TengXun_Secret_Key);
        }

        private string hash_hmac(string signatureString, string secretKey)
        {
            var enc = Encoding.UTF8;
            HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(secretKey));
            hmac.Initialize();

            byte[] buffer = enc.GetBytes(signatureString);
            return Convert.ToBase64String(hmac.ComputeHash(buffer));
        }

        /// <summary>
        /// 将图片转换为base64
        /// </summary>
        /// <param name="bmp"></param>
        /// <returns></returns>
        private string ImageToBase64(Bitmap bmp)
        {
            MemoryStream ms = new MemoryStream();
            bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            byte[] arr = new byte[ms.Length];
            ms.Position = 0;
            ms.Read(arr, 0, (int)ms.Length);
            ms.Close();
            string image = Convert.ToBase64String(arr);
            return image;
        }
    }
}
